package android.olsson.apk;

import android.olsson.apk.R;
import android.olsson.apk.interfaces.IInternetHandler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ApkSystembolagetActivity extends Activity implements
		OnClickListener {

	private Button nameSearchButton;
	private Button conditionSearchButton;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		nameSearchButton = (Button) findViewById(R.id.nameSearchButton);
		conditionSearchButton = (Button) findViewById(R.id.conditionSearchButton);

		nameSearchButton.setOnClickListener(this);
		conditionSearchButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		if (view.equals(nameSearchButton)) {
			startActivity(new Intent(this, NameSearchActivity.class));
		} else if (view.equals(conditionSearchButton)) {
			startActivity(new Intent(this, ConditionSearchActivity.class));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == (R.id.downloadItem)) {
			downloadDatabase();
		}
		return true;
	}

	private void downloadDatabase() {
		final ProgressDialog pd = ProgressDialog.show(this, "System",
				"Uppdaterar databasen...", true, false);
		final Toast notifyToast = Toast.makeText(this,
				"Databasen har uppdaterats.", Toast.LENGTH_SHORT);

		new Thread(new Runnable() {
			public void run() {
				IInternetHandler internetHandler = new InternetHandler();
				internetHandler.downloadDatabase();
				pd.dismiss();
				notifyToast.show();
			}
		}).start();
	}
}